# BSD3.0
# cili@163.com


import socketserver
import socket
import threading

class MyTCPServer:
    def __init__(self,port,request_handler):
        self.server_thread = None
        for tport in range(port,60000):
            try:
                self.server = socketserver.ThreadingTCPServer(('', tport), request_handler)
                self.port = tport
                break
            except socket.error as e:
                pass
        self.server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    def start(self):
        if self.server:
            self.server_thread = threading.Thread(target=self.server.serve_forever)
            self.server_thread.daemon = True
            self.server_thread.start()

    def stop(self):
        if self.server is not None:
            stop_thread = threading.Thread(target=self.stop_server_thread)
            stop_thread.start()

    def stop_server_thread(self):
        if self.server is not None:
            self.server.shutdown()
            self.server.server_close()
            if self.server_thread: self.server_thread.join(2)
            self.server_thread = None
            self.server = None